package org.ccay.security.listener;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.subject.PrincipalCollection;
import org.ccay.core.dispatcher.EventUtil;
import org.ccay.core.exception.ApplicationException;
import org.ccay.core.exception.ExceptionHandler;
import org.ccay.core.request.IAuthenticationFailure;
import org.ccay.core.request.IAuthenticationLogout;
import org.ccay.core.request.IAuthenticationSuccess;
import org.ccay.core.request.UserEventArgs;
import org.ccay.security.entity.User;

public class DefaultAuthenticationListener implements org.apache.shiro.authc.AuthenticationListener{

	@Override
	public void onSuccess(AuthenticationToken token, AuthenticationInfo info) {
		try {
			EventUtil.dispatch(IAuthenticationSuccess.class, this,new UserEventArgs((User)info.getPrincipals().getPrimaryPrincipal()), false);
		} catch (ApplicationException e) {
			ExceptionHandler.logException(e);
		}
	}

	@Override
	public void onFailure(AuthenticationToken token, AuthenticationException ae) {
		try {
			EventUtil.dispatch(IAuthenticationFailure.class, this,new UserEventArgs((User)token.getPrincipal()), false);
		} catch (ApplicationException e) {
			ExceptionHandler.logException(e);
		}
	}

	@Override
	public void onLogout(PrincipalCollection principals) {
		try {
			EventUtil.dispatch(IAuthenticationLogout.class, this,new UserEventArgs((User)principals.getPrimaryPrincipal()), false);
		} catch (ApplicationException e) {
			ExceptionHandler.logException(e);
		}
	}

}